package com.example.demo.util;

import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.stereotype.Component;
import redis.clients.jedis.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class JedisClientPool {
    private static Map<String, JedisPool> jedisPoolMap = new HashMap<String, JedisPool>();

    public static JedisCluster cluster;

    public static Object obj = new Object();

    public static JedisCluster getClusterInstance() {
        if (cluster == null) {
            synchronized (obj) {
                if (cluster == null) {
                    Set<HostAndPort> nodes = new HashSet<>();
                    nodes.add(new HostAndPort("101.201.155.20", 7001));
                    nodes.add(new HostAndPort("101.201.155.20", 7002));
                    nodes.add(new HostAndPort("101.201.155.20", 7003));
                    nodes.add(new HostAndPort("101.201.155.20", 7004));
                    nodes.add(new HostAndPort("101.201.155.20", 7005));
                    nodes.add(new HostAndPort("101.201.155.20", 7006));
                    cluster = new JedisCluster(nodes, 5000,
                            3000, 10, "123456", new JedisPoolConfig());
                }
            }
        }
        return cluster;
    }

    public static JedisPool getInstance(String poolName) {
        JedisPool instance = jedisPoolMap.get(poolName);
        if (instance == null) {
            synchronized (jedisPoolMap) {
                JedisPoolConfig config = new JedisPoolConfig();
                instance = new JedisPool(config, "139.224.74.177", 6379, 0, "I][3^QzL8Dl)[7f", 11);
                jedisPoolMap.put(poolName, instance);
            }
        }
        return instance;
    }

    private static volatile JedisPool jedisPool = null;// 被volatile修饰的变量不会被本地线程缓存，对该变量的读写都是直接操作共享内存。

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisClientPool.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(1000);
                    poolConfig.setMaxIdle(32);
                    poolConfig.setMaxWaitMillis(100 * 1000);
                    poolConfig.setTestOnBorrow(true);

                    jedisPool = new JedisPool(poolConfig, "10.179.201.238", 6379, 0,
                            "foobared114S", 10);
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            Jedis jedis2 = null;
            try {
                jedis2 = jedisPool.getResource();
            } finally {
                jedis2.close();
            }
        }
    }

}
